package com.logicbus.backend.websocket;


import com.anysoft.util.Properties;
import java.util.List;
import org.apache.commons.lang3.StringUtils;

import javax.websocket.Session;
import java.util.Map;

/**
 * 基于websocket会话的Properties
 *
 * @since 1.6.14.1 [20210310 duanyy] <br>
 */
public class SessionProperties extends Properties.Abstract {
    /**
     * 客户端ip
     */
    public static final String CLIENTIP = "$clientIp";

    /**
     * 真实的客户端ip
     */
    public static final String CLIENTIPREAL = "$clientIpReal";

    /**
     * 本次服务的全局序列号
     */
    public static final String SN = "$sn";

    /**
     * 主机信息
     */
    public static final String HOST = "$host";

    /**
     * 主机域名
     */
    public static final String HOST_DOMAIN = "$hostdomain";

    /**
     * 请求方法
     */
    public static final String METHOD = "$method";

    /**
     * 请求参数
     */
    public static final String QUERY = "$query";

    /**
     * 请求完整的URI
     */
    public static final String URI = "$uri";

    /**
     * 请求完整的URL
     */
    public static final String URL = "$url";

    /**
     * 请求的路径
     */
    public static final String PATH = "$path";

    private Session session = null;

    public SessionProperties(Session session,Properties parent){
        super("session", parent);
        this.session = session;
    }

    @Override
    protected void _SetValue(String _name, String _value) {

    }

    @Override
    public void Clear() {

    }

    protected String _GetValue(String name) {
        if (session != null) {
            switch (name) {
                case QUERY:
                    return session.getQueryString();
                case URI:
                    return session.getRequestURI().toString();
            }
            String value = getFromPathParameters(session,name);
            if (StringUtils.isEmpty(value)){
                value = getFromParameters(session,name);
            }
            if (StringUtils.isNotEmpty(value)){
                return value;
            }
        }

        return super._GetValue(name);
    }

    private String getFromParameters(Session session, String name) {
        Map<String,List<String>> map = session.getRequestParameterMap();
        if (map != null){
            List<String> found = map.get(name);
            if (found != null){
                return found.toString();
            }
        }
        return null;
    }

    private String getFromPathParameters(Session session, String name) {
        Map<String,String> map = session.getPathParameters();
        return map == null ? null:map.get(name);
    }
}
